package szcg.scheduled.service.utils;

import org.quartz.*;
import szcg.scheduled.service.entity.JobBean;
import szcg.scheduled.service.task.PushHandleCaseJob;

import java.util.HashMap;

import static org.quartz.JobKey.jobKey;

public class JobBuildHelp {

    public static final HashMap<String, JobBean> JobMap = new HashMap<>() {
        {
            //推送案件任务
            JobBean pushTask = new JobBean();
            pushTask.jobKey = jobKey("pushCaseJob", "taskGroup");
            pushTask.triggerKey = TriggerKey.triggerKey("pushCaseTrigger", "taskGroup");
            pushTask.jobDetail = JobBuilder.newJob(PushHandleCaseJob.class).withIdentity(pushTask.jobKey).build();
            put("100001", pushTask);

            //其他任务
        }
    };

    /**
     * 构建Trigger
     *
     * @param triggerKey TriggerKey
     * @param cron       cron
     * @return Trigger
     */
    public static Trigger generateTrigger(TriggerKey triggerKey, String cron) {
        return TriggerBuilder.newTrigger()//
                .withIdentity(triggerKey)//
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))//
                //极短的时间间隔内，Quartz调度器可能会多次检查并执行与触发器相关联的作业会触发多次
                // 10秒后生效，要不然调度启动后如果延迟，可能出现首次执行多遍job
                .startAt(DateBuilder.futureDate(10, DateBuilder.IntervalUnit.SECOND))//
                .build();
    }

    /**
     * @param cronExpression cronExpression
     * @return HashMap
     */
    public static HashMap<String, String> isValid(String cronExpression) {
        HashMap<String, String> resMap = new HashMap<>();
        try {
            new CronExpression(cronExpression);
            resMap.put("state", "000");
            resMap.put("msg", "校验通过");
            return resMap;
        } catch (Exception e) {
            resMap.put("state", "111");
            resMap.put("msg", "校验不通过：" + "Invalid cron expression: " + e.getMessage());
            return resMap;
        }
    }

}
